package com.chaucer.demo.datasource;

import com.chaucer.demo.enums.BusinessSourceEnum;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;


import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author Chaucer
 * @Date 2021/9/2 18:05
 */
@Slf4j
@ComponentScan(basePackages = "com.chaucer.demo")
@MapperScan("com.chaucer.demo.mapper")
@Configuration
public class DynamicDataSourceAutoConfiguration {
    @Bean(name = "dataSource")
    public DataSource dataSource(Environment env) {
        MultiDataSource multipleDataSource = new MultiDataSource(DataSourceUtils::selectDataSource);
        Map<Object, Object> dataSourceMap = new HashMap<>();
        BusinessSourceEnum[] values = BusinessSourceEnum.values();
        for (BusinessSourceEnum value : values) {
            try {
                DataSource dataSource = DataSourceUtils.getDataSourceFromJDBC(env, value.getCode());
                if (dataSource != null) {
                    dataSourceMap.put(value.getCode() + DataSourceUtils.DATASOURCE_SUFFIX, dataSource);
                }else {
                    //默认数据源
                }
            } catch (Exception e) {
                log.warn("数据源{}加载失败，请查看配置是否正确", value.getCode());
            }
        }
        log.info("多数据源加载完成{}", dataSourceMap.keySet());
        multipleDataSource.setTargetDataSources(dataSourceMap);
        return multipleDataSource;
    }
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean;
    }
}